const constants     = require("../../db/constants");
const sipServer     = require('../../sip/server/server');
const log4js        = require('../../utils/logUtils');
const logger        = log4js.getLogger('request');
const cpuStat       = require('cpu-stat');
const osutils       = require('os-utils');
const basectrl    = require('./basectrl');
const deviceCache = require("../../db/deviceCache");

let Service={};
const TAG = "[服务状态控制器]";
/**
 * 改变Service服务的状态
 * @param {*} req
 * @param {*} res
 */
Service.changeStatus=function(req,res){
    if(!basectrl.hasLogin(req, res)){
        return;
    }
    logger.info("API请求 改变service状态");
    if(sipServer.running){
        sipServer.stop();
    }else{
        sipServer.start();
    }
    let ret=Object.assign(constants.httpCode.OK,{
        data:{"running": sipServer.running}
    });
    res.send(ret);
}
/**
 * 获取Service服务的状态
 * @param {*} req
 * @param {*} res
 */
Service.getStatus=function(req,res){
    if(!basectrl.hasLogin(req, res)){
        return;
    }
    const mem = 100*(osutils.totalmem()-osutils.freemem())/osutils.totalmem();

    cpuStat.usagePercent(function(err, percent) {
       if (err) {
           return logger.log(TAG, err);
       }
       let ret=Object.assign(constants.httpCode.OK,{
            data: {
                running: sipServer.running,
                start: constants.start,
                cpu_usage: percent,
                mem_usage: mem,
                mem_total: osutils.totalmem(),
                mem_free : osutils.freemem()
            }
        });
    res.send(ret);
   });
}
/**
 * 获取连接的Service客户端
 * @param {*} req
 * @param {*} res
 */
Service.getClients=function(req,res){
    if(!basectrl.hasLogin(req, res)){
        return;
    }
    let ret=Object.assign(constants.httpCode.OK,{
        data:deviceCache.registry
    });
    res.send(ret);
}
module.exports=Service;
